/**
 * @brief: 
 *
 * @author: dariaye@tencent.com
 * @date: 2012-8-13
 * @version: 1.0
 * @changes:
 *    <author>        <time>        <version >        <desc>
 *     dariaye             2012-8-13              1.0                 Create
 *
 */

#include <stdlib.h>
#include <string.h>

#include "critical_section.h"

CriticalSection::CriticalSection() : m_critical_data(NULL), m_capacity(0)
{
}

CriticalSection::~CriticalSection()
{
}

bool CriticalSection::Init(WLUInt capacity)
{
    m_capacity = capacity;
    m_critical_data = new unsigned char[capacity];
    memset(m_critical_data, 0, capacity);

    return true;
}

void CriticalSection::UnInit()
{
    if(m_critical_data)
        delete [] m_critical_data;

    m_critical_data = NULL;
    m_capacity = 0;
}

void CriticalSection::Lock(WLUInt index)
{
    if(m_critical_data)
    {
        while(TestAndSet(&m_critical_data[index]));
    }
}

void CriticalSection::UnLock(WLUInt index)
{
    if(m_critical_data)
        m_critical_data[index] = 0x00;
}

int CriticalSection::TestAndSet(unsigned char* addr)
{
    unsigned char result = 1;
    asm("xchgb %1, %0":"=m" (*addr),"=r" (result):"1" (result) :"memory");
    return result;
}
